package com.huawei.crm.util;

import com.huawei.crm.domain.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * 对象构建生成
 *
 * @author luohua
 * @date 2021年12月10日14:34:18
 * @desc
 */
public class ObjectBuilderHelper<T> {

    private final Supplier<T> instantiate;

    private final List<Consumer<T>> modifiers = new ArrayList<>();

    public ObjectBuilderHelper(Supplier<T> instantiate) {
        this.instantiate = instantiate;
    }

    public static <T> ObjectBuilderHelper<T> of(Supplier<T> instantiate) {
        return new ObjectBuilderHelper<>(instantiate);
    }

    public <P1> ObjectBuilderHelper<T> with(Consumer1<T, P1> consumer, P1 p1) {
        Consumer<T> c = instance -> consumer.accept(instance, p1);
        modifiers.add(c);
        return this;
    }

    public <P1, P2> ObjectBuilderHelper<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
        modifiers.add(c);
        return this;
    }

    public <P1, P2, P3> ObjectBuilderHelper<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
        modifiers.add(c);
        return this;
    }

    public T build() {
        T value = instantiate.get();
        modifiers.forEach(modifier -> modifier.accept(value));
        modifiers.clear();
        return value;
    }

    /**
     * 1 参数 Consumer
     */
    @FunctionalInterface
    public interface Consumer1<T, P1> {
        void accept(T t, P1 p1);
    }

    /**
     * 2 参数 Consumer
     */
    @FunctionalInterface
    public interface Consumer2<T, P1, P2> {
        void accept(T t, P1 p1, P2 p2);
    }

    /**
     * 3 参数 Consumer
     */
    @FunctionalInterface
    public interface Consumer3<T, P1, P2, P3> {
        void accept(T t, P1 p1, P2 p2, P3 p3);
    }

    public static void main(String[] args) {
        Employee employee = ObjectBuilderHelper.of(Employee::new)
                .with(Employee::setName, "丽丽")
                .with(Employee::setAge, 18)
                .with(Employee::setEmail, "eeeq@163.com")
                .with(Employee::setPassword, "sgs")
                .build();

        System.out.println("employee = " + employee);

    }
}
